package com.laomuji.android.mvvm.demo.web

import androidx.lifecycle.MutableLiveData
import com.laomuji.android.mvvm.base.BaseActivity
import com.laomuji.android.mvvm.base.BaseActivityViewModel
import com.laomuji.android.mvvm.http.ServiceManager
import com.laomuji.android.mvvm.http.entity.request.TestRequestEntity
import com.laomuji.android.mvvm.http.entity.response.TestResponseEntity
import com.laomuji.android.mvvm.http.observer.BaseObserver
import com.laomuji.android.mvvm.http.observer.observeOnIO
import com.laomuji.android.mvvm.http.observer.observeOnMain
import com.trello.rxlifecycle2.android.ActivityEvent
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


/**
 * 一些Http请求的包装
 *
 * 1.需要更新ui
 *   使用回调的方式,例子:[facebookEvent]
 *   绑定生命周期:[BaseActivity.bindUntilEvent]
 * 2.需要更新ui
 *   使用LiveData的方式,例子:[uploadFileToAliOss],[uploadFiles]
 *   绑定生命周期:[MutableLiveData.postValue]切换主线程,[MutableLiveData.observe]监听数据变化
 * 3.不需要更新ui,[postFrom],[postJson],[postEncode]
 *
 * @author laomuji666
 * @since 2024/3/28
 */
class HttpViewModel:BaseActivityViewModel() {
    /**
     * 上传阿里oss是否成功
     */
    val uploadALiOssLiveData = MutableLiveData<Boolean>()

    /**
     * 批量上传文件是否成功
     */
    val uploadFilesLiveData = MutableLiveData<String>()

    /**
     * @param activity 绑定生命周期
     * @param id 像素id
     * @param event 事件名称
     */
    fun facebookEvent(activity:BaseActivity<*,*>,id:String,event:String, callback:(Boolean)->Unit){
        //observeOnMain 网络请求在io线程,回调在ui线程

        ServiceManager.getService().facebookEvent("tr",id,event)
            .observeOnMain()
            .compose(activity.bindUntilEvent(ActivityEvent.DESTROY))
            .subscribe(object : BaseObserver<String>(){
                override fun onSuccess(entity: String) {
                    callback(true)
                }

                override fun onFail(code: String, msg: String, e: Throwable) {
                    callback(false)
                    e.printStackTrace()
                }
            })
    }

    /**
     * @param activity 绑定生命周期
     * @param type 类型,表单参数
     * @param email 邮件,表单参数
     */
    fun postFrom(activity:BaseActivity<*,*>, type:Int, email:String){
        //observeOnIO 网络请求在io线程,回调在io线程

        val map:HashMap<String, String> = HashMap()
        map["type"] = type.toString()
        map["email"] = email
        ServiceManager.getService().fromLogin(map)
            .observeOnIO()
            .compose(activity.bindUntilEvent(ActivityEvent.DESTROY))
            .subscribe(object : BaseObserver<TestResponseEntity>(){
                override fun onSuccess(entity: TestResponseEntity) {}
                override fun onFail(code: String, msg: String, e: Throwable) {}
            })
    }

    /**
     * @param activity 绑定生命周期
     * @param type 类型,Json参数
     * @param email 邮件,Json参数
     */
    fun postJson(activity:BaseActivity<*,*>, type:Int, email:String){
        val testRequestEntity = TestRequestEntity()
        testRequestEntity.type = type
        testRequestEntity.email = email
        ServiceManager.getService().jsonLogin(testRequestEntity)
            .observeOnIO()
            .compose(activity.bindUntilEvent(ActivityEvent.DESTROY))
            .subscribe(object : BaseObserver<TestResponseEntity>(){
                override fun onSuccess(entity: TestResponseEntity) {}
                override fun onFail(code: String, msg: String, e: Throwable) {}
            })
    }


    /**
     * @param activity 绑定生命周期
     * @param type 类型,Json参数
     * @param email 邮件,Json参数
     */
    fun postEncode(activity:BaseActivity<*,*>, type:Int, email:String){
        val testRequestEntity = TestRequestEntity()
        testRequestEntity.type = type
        testRequestEntity.email = email
        ServiceManager.getService().encodeBody(testRequestEntity)
            .observeOnIO()
            .compose(activity.bindUntilEvent(ActivityEvent.DESTROY))
            .subscribe(object : BaseObserver<TestResponseEntity>(){
                override fun onSuccess(entity: TestResponseEntity) {}
                override fun onFail(code: String, msg: String, e: Throwable) {}
            })
    }


    /**
     * @param uploadUrl 上传路径,后台下发,只可以使用一次
     * @param file 需要上传的文件
     */
    fun uploadFileToAliOss(uploadUrl:String, file:File){
        val requestBody: RequestBody = RequestBody.create(MediaType.parse("video/*"), file)
        ServiceManager.getService()
            .uploadOSS(uploadUrl,requestBody)
            .observeOnIO()
            .subscribe(object :BaseObserver<String>(){
                override fun onSuccess(entity: String) {
                    //上传成功
                    uploadALiOssLiveData.postValue(true)
                }

                override fun onFail(code: String, msg: String, e: Throwable) {
                    //上传失败,阿里OSS返回错误码
                    uploadALiOssLiveData.postValue(false)
                }
            })
    }


    /**
     * @param fileList 需要上传的图片文件列表
     */
    fun uploadFiles(fileList: List<File>){
        val partList = ArrayList<MultipartBody.Part>()
        for (file in fileList) {
            val requestBody = RequestBody.create(MediaType.parse("image/*"), file)
            partList.add(MultipartBody.Part.createFormData("files", file.getName(), requestBody))
        }
        ServiceManager.getService()
            .uploadFiles("1", partList.toTypedArray())
            .observeOnIO()
            .subscribe(object :BaseObserver<String>(){
                override fun onSuccess(entity: String) {
                    //一般后台会返回多个上传成功的路径,具体根据返回的数据解析
                    uploadFilesLiveData.postValue(entity)
                }

                override fun onFail(code: String, msg: String, e: Throwable) {}
            })
    }
}